﻿namespace Pibby.Core.Playlist
{
    using System;
    using System.IO;
    using System.Xml;

	public static class WindowsPlaylistReader
	{
		public static MediaPlaylist LoadFrom(TextReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader", Resources.WindowsPlaylist_BlankObjectError);

			using (var xmlReader = XmlReader.Create(reader))
			{
				var document = new XmlDocument();

				document.Load(xmlReader);

				return Load(document);
			}
		}

		private static MediaPlaylist Load(XmlDocument document)
		{
			const string SrcAttribute = "src";
			const string TidAttribute = "tid";

			var playlist = new MediaPlaylist();

			XmlNodeList nodeList = document.SelectNodes("smil/body/seq/media");

			foreach (XmlNode node in nodeList)
			{
				string path = string.Empty;
				string id = string.Empty;

				if (node.Attributes[SrcAttribute] != null)
				{
					path = node.Attributes[SrcAttribute].Value;
				}

				if (node.Attributes[TidAttribute] != null)
				{
					id = node.Attributes[TidAttribute].Value;
				}

				PlaylistItem newItem = null;

				if (!string.IsNullOrEmpty(path))
				{
					if (!string.IsNullOrEmpty(id))
					{
						newItem = new PlaylistItem(path, id);
					}
					else
					{
						newItem = new PlaylistItem(path);
					}
				}

				if (newItem != null)
					playlist.Items.Add(newItem);
			}

			return playlist;
		}

	}
}
